<template>
  <el-card>
    <el-row>
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="danger" style="margin-right: 10px" @click="handleBulkDelete">批量删除</el-button>
      <el-input v-model="data.keyword" placeholder="岗位名称" style="width: 200px; margin-right: 10px">
        <template #prefix>
          <el-icon class="el-input__icon">
            <search/>
          </el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button type="warning" @click="handleEmpty">清空</el-button>
    </el-row>
    <el-table
        v-loading="data.loading === true"
        :data="data.tableData"
        v-if="data.tableData.length > 0"
        style="width: 100%; margin-top: 10px; overflow: hidden" @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" sortable min-width="50"></el-table-column>
      <el-table-column prop="id" label="序号" sortable min-width="100"></el-table-column>
      <el-table-column prop="title" label="岗位名称" sortable min-width="100"></el-table-column>
      <el-table-column prop="cover" label="公司名称" sortable min-width="100"></el-table-column>
      <el-table-column prop="salary" label="薪资水平" sortable min-width="100"></el-table-column>
      <el-table-column prop="description" label="岗位描述" min-width="100"></el-table-column>
      <el-table-column prop="education" label="学历要求" sortable min-width="100"></el-table-column>
      <el-table-column prop="workExpe" label="经验要求" sortable min-width="100"></el-table-column>
      <el-table-column prop="location" label="工作地点" sortable></el-table-column>
      <el-table-column label="操作" min-width="100">
        <template #default="scope">
          <el-button-group>
            <el-button size="default" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="default" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <el-empty v-else :image-size="200"></el-empty>
    <div v-if="data.total" style="margin-top: 10px">
      <el-pagination
          background
          small
          :page-size="data.pageSize"
          :current-page="data.pageNum"
          layout="total,prev, pager, next,jumper"
          :total="data.total"
          @current-change="handleCurrentChange"
      ></el-pagination>
    </div>


<!--    弹窗-->
    <el-dialog v-model="data.formVisible" title="岗位信息" width="50%" destroy-on-close :center="true">
      <el-form :model="data.form" label-width="100px" ref="ruleFormRef" :rules="data.rules" >
        <el-form-item label="岗位名称" prop="title">
          <el-input v-model="data.form.title" placeholder="请输入"/>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="分类" name="classificationId">
              <el-select
                  v-if="data.formVisible && data.cData.length > 0"
                  clearable
                  v-model="data.form.classificationId"
                  placeholder="请选择">
                <el-option
                    v-for="item in data.cData"
                    :key="item.value"
                    :label="item.title"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标签">
              <el-select
                  v-if="data.formVisible && data.tagData.length > 0"
                  multiple
                  clearable
                  v-model="data.form.tags"
                  placeholder="请选择">
                <el-option
                    v-for="item in  data.tagData"
                    :key="item.value"
                    :label="item.title"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="岗位描述">
        <el-input v-model="data.form.description" autocomplete="off" type="textarea"  placeholder="请输入"/>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工作地点">
              <el-input v-model="data.form.location" placeholder="请输入"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="薪资水平">
              <el-input v-model="data.form.salary"  placeholder="请输入"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="学历要求" name="education">
              <el-select v-if="data.formVisible" v-model="data.form.education" allowClear placeholder="请输入">
                <el-option key="不限" value="不限">不限</el-option>
                <el-option key="专科" value="专科">专科</el-option>
                <el-option key="本科" value="本科">本科</el-option>
                <el-option key="研究生" value="研究生">研究生</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经验要求" name="workExpe">
              <el-select v-if="data.formVisible" v-model="data.form.workExpe" allowClear placeholder="请输入">
              <el-option key="不限" value="不限">不限</el-option>
              <el-option key="1-3年" value="1-3年">1-3年</el-option>
              <el-option key="3-5年" value="3-5年">3-5年</el-option>
              <el-option key="5年以上" value="5年以上">5年以上</el-option>
            </el-select>
            </el-form-item>
        </el-col>
          <el-col :span="12">
            <el-form-item label="状态" name="status">
              <el-select v-if="data.formVisible" placeholder="请选择" allowClear v-model="data.form.status">
                <el-option key="0" value="上架">上架</el-option>
                <el-option key="1" value="下架">下架</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="Formcancel">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { Search } from "@element-plus/icons-vue";
import {nextTick, onMounted, reactive, ref} from "vue";
import {createApi, deleteApi, listApi, updateApi} from "@/api/thing";
import { listApi as listClassificationApi} from "@/api/classification";
import { listApi as listTagApi} from "@/api/tag";
import {ElMessage, ElMessageBox} from "element-plus";


const data = reactive({
  tableData: [],
  loading: false,
  editFlag:false,
  total: 0,
  pageNum: 1,
  pageSize: 10,
  formVisible: false,
  cData:[],
  tagData: [{}],
  form: {
    id: undefined,
    title: undefined,
    cover: undefined,
    classificationId: undefined,
    tags: [],
    status: undefined,
    location: undefined,
    salary: undefined,
    workExpe: undefined,
    education: undefined,
  },
  keyword: '',
  rules: {
    title: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  },
  selectedRowKeys: []
});
onMounted(async () => {
  await dataload();
  await nextTick(async () => {
    await getCDataList();
    await getTagDataList();
  });

});

const ruleFormRef = ref()
const dataload = async () => {
  data.loading=true;
  setTimeout(() => {
    data.loading = false;
  }, 1000);
  await listApi({
    pageNum: data.pageNum,
    pageSize: data.pageSize,
    keyword: data.keyword
  }).then(res => {
    data.tableData = res.data.list;
    data.total=res.data.total;
    data.pageNum=res.data.pageNum;
    data.pageSize=res.data.pageSize;
  }).catch(err => {
    console.log(err);
    ElMessage.error('数据加载错误',err);
  });
};


const getCDataList = () => {
  listClassificationApi({}).then(res => {
    data.cData = res.data.list;
    // console.log("cData", data.cData);
  }).catch(err => {
    console.log(err);
    ElMessage.error('获取分类数据失败');
  });
};

const getTagDataList = () => {
  listTagApi({}).then(res => {
    res.data.list.forEach((item, index) => {
      item.index = index + 1;
    });
    data.tagData = res.data.list;
    // console.log("tableData", data.tagData);
  }).catch(err => {
    console.log(err);
    ElMessage.error('获取标签数据失败');
  });
};
const handleSearch=()=>{
  dataload();
}
const handleEmpty=()=>{
  data.keyword='';
  dataload();
}

const handleAdd=()=>{
  data.editFlag=false;
  FormClear();
  data.formVisible=true;
}
const handleBulkDelete=()=>{
  if (data.selectedIds===undefined||data.selectedIds.length===0){
    ElMessage.warning("请选择要删除的岗位");
    return;
  }
  // 将数组转换为逗号分隔的字符串
  const idsParam = data.selectedIds.join(',');
  console.log(idsParam)
  ElMessageBox.confirm('确认删除选中的用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      const res = await deleteApi({'ids': idsParam})
      if (res.code === 200) {
        ElMessage.success(res.msg);
        dataload();
      }else {
        ElMessage.error(res.msg);
      }
    } catch (err) {
      console.error(err);
    }
  })
}
const handleSelectionChange = (selection) => {
  data.selectedIds = selection.map(item => item.id);
};
const FormClear=()=>{
  // 重置整个表单数据，确保所有表单项包括选择器恢复默认或初始状态
  data.form = {
    id: undefined,
    title: undefined,
    cover: undefined,
    classificationId: undefined, // 这里会重置分类选择器的值
    tags: [], // 这里会清空标签多选框的值
    status: undefined,
    location: undefined,
    salary: undefined,
    workExpe: undefined,
    education: undefined
  };
}

const Formcancel = () => {
  FormClear();
  // 隐藏弹窗
  data.formVisible = false;
};

const save=async () => {
  try {
    const isValid = await ruleFormRef.value.validate(); // 手动触发验证
    if (!isValid) {
      return; // 如果验证失败，则不执行后续的保存逻辑
    }
    // 创建FormData实例
    const formData = new FormData();

    // 将表单数据逐个添加到formData中
    if(data.editFlag) {
      formData.append('id', data.form.id)
    }
    formData.append('title', data.form.title)
    if (data.form.classificationId) {
      formData.append('classificationId', data.form.classificationId)
    }
    if (data.form.tags) {
      data.form.tags.forEach(function (value) {
        if(value){
          formData.append('tags[]', value)
        }
      })
    }
    if (data.form.imageFile) {
      formData.append('imageFile', data.form.imageFile)
    }
    formData.append('description', data.form.description || '')
    // formData.append('price', data.form.price || '')
    // if (data.form.repertory >= 0) {
    //   formData.append('repertory', data.form.repertory)
    // }
    if (data.form.status) {
      if (data.form.status === '上架') {
        data.form.status = '0';
      } else if (data.form.status === '下架') {
        data.form.status = '1';
      }
      formData.append('status', data.form.status)
    }
    if (data.form.location) {
      formData.append('location', data.form.location)
    } if (data.form.salary) {
      formData.append('salary', data.form.salary)
    } if (data.form.workExpe) {
      formData.append('workExpe', data.form.workExpe)
    } if (data.form.education) {
      formData.append('education', data.form.education)
    }


    if (data.editFlag){
      await updateApi(formData).then(res=>{
        // console.log(res)
        if (res.code === 200){
          ElMessage.success(res.msg);
          Formcancel();
          dataload();
        }else{
          ElMessage.error(res.msg);
        }
      })
    }else{
      await createApi(formData).then(res=>{
        // console.log(res)
        if (res.code === 200){
          ElMessage.success(res.msg);
          Formcancel();
          dataload();
        }else{
          ElMessage.error(res.msg);
        }
      })
    }
  }catch (err){
    console.error(err);
  }
}
const handleCurrentChange = (number) => {
  data.pageNum = number
  dataload()
}

const handleEdit = (row) => {
  data.editFlag=true;
  data.form=JSON.parse(JSON.stringify(row));
  data.form.id=row.id;
  data.formVisible=true;
}
const handleDelete=(row)=>{
  ElMessageBox.confirm("删除后数据无法恢复，确认删除？", "警告", {type: 'warning'})
      .then(async () => {
        try {
          await deleteApi({"ids":row.id}).then(res=>{
            if (res.code===200){
              ElMessage.success('删除成功')
              dataload();
            }else {
              ElMessage.error(res.msg)
            }
          })
        }catch (err){
          console.error('请求错误',err);
        }
      }).catch(err=>{
    ElMessage.info('取消');
  })
}

</script>
<style scoped>
.dialog-footer {
  text-align: right;
}
</style>